package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.thirdpush.GenerateTestUserSig;
import com.jaya.budan.utils.LoadingDialog;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushSettings;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_login_mobile, et_login_password;
    private TextView tv_login_go_register, tv_login_forget_password, tv_login_privacy, tv_login_user_xieyi;
    private Button btn_login;
    private ImageView iv_login_cha;
    private RelativeLayout rl_login_mobile;
    private String access_token;
    private LoadingDialog dialog;
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 1000L;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        et_login_mobile = findViewById(R.id.et_login_mobile);
        et_login_password = findViewById(R.id.et_login_password);
        tv_login_go_register = findViewById(R.id.tv_login_go_register);
        tv_login_forget_password = findViewById(R.id.tv_login_forget_password);
        tv_login_privacy = findViewById(R.id.tv_login_privacy);
        tv_login_user_xieyi = findViewById(R.id.tv_login_user_xieyi);
        iv_login_cha = findViewById(R.id.iv_login_cha);
        rl_login_mobile = findViewById(R.id.rl_login_mobile);
        btn_login = findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        tv_login_go_register.setOnClickListener(this);
        tv_login_forget_password.setOnClickListener(this);
        tv_login_privacy.setOnClickListener(this);
        tv_login_user_xieyi.setOnClickListener(this);
        iv_login_cha.setOnClickListener(this);
        rl_login_mobile.setOnClickListener(this);
        et_login_mobile.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && et_login_mobile.getText().length()>0){
                    iv_login_cha.setVisibility(View.VISIBLE);
                }else{
                    iv_login_cha.setVisibility(View.INVISIBLE);
                }
            }
        });
        boolean bool = VolleyUtil.isNetworkConnected(this);
//        if (bool){
//            ToolUtils.showToast(this, "网络可用");
//        } else {
//            ToolUtils.showToast(this, "网络不可用");
//        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData(JSONObject object) {
        Log.d("login", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.login_Url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("login", jsonObject.toString());
                dialog.dismiss();//关闭加载动画
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        access_token = info.getString("access_token");
                        int id = info.getInt("id");
                        boolean is_over = info.getBoolean("is_over");
                        if (is_over){
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);//资料完整,跳转首页
                            intent.putExtra("access_token", access_token);
                            startActivity(intent);
                            finish();
                        } else {
                            Intent intent = new Intent(LoginActivity.this, Fill_Information_Activity.class);//资料不完整，自动跳转至资料填写页面
                            intent.putExtra("access_token", access_token);
                            startActivity(intent);
                        }
                        JSONObject object = new JSONObject();
                        try {
                            object.put("reg_id", JPushInterface.getRegistrationID(LoginActivity.this));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        postUploadJpushData(object, id + "");
                        // 获取userSig函数
                        String userSig = GenerateTestUserSig.genTestUserSig(id + "");
                        TIMManager.getInstance().login(id + "", userSig, new TIMCallBack() {
                            @Override
                            public void onError(int code, String desc) {
                                ToolUtils.showToast(LoginActivity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                                if (code == 6208){
                                    Log.d("login", "被其他人踢开");
                                }
                            }

                            @Override
                            public void onSuccess() {
//                                ToolUtils.showToast(LoginActivity.this, "登录成功");
                            }
                        });
                        SharedPreferences preferences = getSharedPreferences("user_limit", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("username", et_login_mobile.getText().toString().trim());
                        editor.putString("password", et_login_password.getText().toString().trim());
                        editor.apply();
                        TUIKit.login(id + "", userSig, new IUIKitCallBack() {
                            @Override
                            public void onError(String module, final int code, final String desc) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        ToolUtils.showToast(LoginActivity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                                    }
                                });
                                ToolUtils.showToast(LoginActivity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                            }
                            @Override
                            public void onSuccess(Object data) {
                                ToolUtils.showToast(LoginActivity.this, "登录成功");
                                TIMOfflinePushSettings settings = new TIMOfflinePushSettings();
                                //开启离线推送
                                settings.setEnabled(true);
                                //设置收到 C2C 离线消息时的提示声音，以把声音文件放在 res/raw 文件夹下为例
                                settings.setC2cMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.ic_launcher_background));
                                //设置收到群离线消息时的提示声音，以把声音文件放在 res/raw 文件夹下为例
//                                settings.setGroupMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.ic_launcher_background));
                                TIMManager.getInstance().setOfflinePushSettings(settings);
                                TIMManager.getInstance().getConversation(
                                        TIMConversationType.C2C,    //会话类型：单聊
                                        id+"");
                            }
                        });
                    } else {
                        ToolUtils.showToast(LoginActivity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(LoginActivity.this, "网络请求失败，请稍后重试~");
                dialog.dismiss();//关闭加载动画
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postUploadJpushData(JSONObject object, String uid) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.upload_Jpush_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("login", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JPushInterface.setAlias(getApplicationContext(), uid, new TagAliasCallback() {
                            @Override
                            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                            }
                        });
                    } else {
                        ToolUtils.showToast(LoginActivity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(LoginActivity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                if (ToolUtils.isEmpty(et_login_mobile.getText().toString().trim())) {
                    ToolUtils.showToast(LoginActivity.this, "手机号不能为空");
                    return;
                }
                if (! ToolUtils.isChinaMobile(et_login_mobile.getText().toString().trim(), LoginActivity.this)){
                    ToolUtils.showToast(LoginActivity.this,"手机号格式有误，请重新输入！");
                    return;
                }
                if (ToolUtils.isEmpty(et_login_password.getText().toString().trim())) {
                    ToolUtils.showToast(LoginActivity.this, "密码不能为空");
                    return;
                }
                long nowTime = System.currentTimeMillis();//防止按钮重复点击
                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    // do something
                    mLastClickTime = nowTime;
                    dialog = new LoadingDialog(this);
                    dialog.setMessage("正在登录...").show();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    JSONObject object = new JSONObject();
                    try {
                        object.put("username", et_login_mobile.getText().toString().trim());
                        object.put("password", et_login_password.getText().toString().trim());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    postData(object);
                } else {
                    ToolUtils.showToast(this, "不要重复点击");
                }
                break;
            case R.id.tv_login_go_register:
                Intent intent = new Intent(LoginActivity.this, Register_Activity.class);
                startActivity(intent);
                break;
            case R.id.tv_login_forget_password:
                Intent intent2 = new Intent(LoginActivity.this, Forget_Password_Activity.class);
                startActivity(intent2);
                break;
            case R.id.iv_login_cha:
                et_login_mobile.setText("");
                iv_login_cha.setVisibility(View.INVISIBLE);
                break;
            case R.id.tv_login_privacy:
                Intent intent3 = new Intent(LoginActivity.this, Privacy_WebView_Activity.class);
                intent3.putExtra("access_token", access_token);
                intent3.putExtra("type", 3);//隐私条款
                startActivity(intent3);
                break;
            case R.id.tv_login_user_xieyi:
                Intent intent4 = new Intent(LoginActivity.this, Privacy_WebView_Activity.class);
                intent4.putExtra("access_token", access_token);
                intent4.putExtra("type", 1);//不单用户条款
                startActivity(intent4);
                break;
            case R.id.rl_login_mobile:
                ToolUtils.showSoftInputFromWindow(et_login_mobile);
                break;
            default:
                break;
        }
    }
}
